package core

class AccountController {
	
	static layout = 'country'

    def index() { 
		
		def max = params.long('max')?:10
		def start = params.long('start')?:0
		[accounts:Account.list(max: max, offset:start ),max:max, start:start ]
	}
	
	
	def createUser()
	{
		
		
	}
	
	def update() {
		def account =  Account.get(params.long('id'))
		account.properties = params
		if(account.save()) {
			flash.notice = "User: ${account.username} was updated"
			redirect action:'index'
		}
		else {
			flash.error = "User:  failed to be update"
			render(view:'editDoc',model:[account: account])
		}
	}
	
	def editUser()
	{
		[account: Account.get(params.long('id'))]
	}
	
	def deleteUser()
	{
	def account =  Account.get(params.id)
	   
		account.delete()
		redirect(action:'index')
	}
	
	
	def authenticate(String username, String password) {
		def user =  Account.findByUsernameAndPassword("${username}", "${password}")
		if(user){
			session.user = user
			flash.welcome = "Welcome ${user.username}"
			redirect (action:'list')
		}
		else {
			flash.loginStatus="login failed: incorrect user name or password"
			redirect(action:'login')
		}

	}
	def login(){
		render(view:'Login')
	}
	def save() {
		def user = new Account(params)
		
		if (user.save()) {
			flash.notice = "User ${user.username}: is saved successfuly"
			redirect(action:'login')
		} else {
			flash.error = "User ${user.username}: Failed to save"
			render view:'createUser', model:[user:user]
		}
	}
	
	def show() {
		
				[account: Account.get(params.long('id'))]
			}
	def list () {
		[accounts: Account.list()]
	}
}
